﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PHPDecoder;
using System.Threading;
using System.IO;

namespace CodeVisual
{
    public partial class CodeVisual : Form
    {
        TreeNode fileTree = null;
        Thread th = null;
        myDecoder d = null;
        Label l = new Label();
        Output o = null;

        public CodeVisual()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            Init();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ProjectInfo.modified)
            {
                DialogResult res = MessageBox.Show("The project was modified, Save it ?", "Save", MessageBoxButtons.YesNoCancel);
                if (res == DialogResult.Cancel) return;
                if (res == DialogResult.Yes) ProjectInfo.SaveProject();
            }

            Application.Exit();
        }

        /// <summary>
        /// Inicializacia projektu, nacitanie nastavenia.
        /// </summary>
        private void Init()
        {
            Setting.Load();
            toolTip1.SetToolTip(button3, "Add Folder");
            toolTip1.SetToolTip(button2, "Delete selected");
            toolTip1.SetToolTip(button4, "Import source file");
        }
        private delegate void MyInvokeDelegate();
        private void button1_Click(object sender, EventArgs e)
        {
            if (ProjectInfo.rootDir == null) return;
            //Analyze
            foreach (FileNode f in ProjectInfo.rootDir.subtree.Values)
            {
                if (f.startup)
                {
                    String path = ProjectInfo.getAbsolutePath(f.path);
                    //l.Text = "Analyzing...";
                    //l.Parent = outPanel;
                    ////outPanel.Invoke(new );
                    d = new myDecoder(path);
                    //outPanel.Invoke(new MyInvokeDelegate(CallBack));
                    //Thread th = new Thread(new ThreadStart(Decode));
                    ////th.IsBackground = true;
                    //th.Start();
                    ////mi = new MethodInvoker(Decode);
                    ////mi.BeginInvoke(CallBack, null);
                    ////progressBar1.Value = 100;
                    Decode();
                    button1.Enabled = true;
                }
            }
        }

        private void Decode()
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            ProjectInfo.result = d.Decode();
            l.Parent = null;
            l = null;

            progressBar1.Value = 100;

            foreach (string ss in ProjectInfo.result.decodedFile.Keys)
            {
                o = new Output(ss);
                outPanel.Controls.Add(o);
            }
        }
        private void browseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //toolStripStatusLabel1.Text = e.ToString();
            //fnfwarning.Text += treeView1.SelectedNode.Text;
        }

        private void optionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SettingDialog setdial = new SettingDialog();
            DialogResult res = setdial.ShowDialog();
        }

        private void name_MouseHover(object sender, EventArgs e)
        {
            statusStrip1.Text = ((Output)sender).Name;
        }

        private void openProjectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "CodeVisual Project (.cvp) | *.cvp";
            DialogResult res = ofd.ShowDialog();

            if (res == DialogResult.Cancel) return;

            ProjectInfo.reset();
            ProjectInfo.path = ofd.FileName;

            if (!ProjectInfo.AnalyseProjectFile())
            {
                (new ErrorBox(100, 300, "Error: Bad project file !")).ShowDialog();
                fileTree = null;
                projectTreeView.Nodes.Clear();
                //projectTreeView.Nodes.Add(fileTree);
            }
            else
            {
                TreeNode node = new TreeNode(ProjectInfo.name);
                projectTreeView.Nodes.Clear();
                projectTreeView.Nodes.Add(node);
                ShowProjectFileNodes(ProjectInfo.rootDir, node);
                projectTreeView.ExpandAll();
            }
        }

        private void ShowProjectFileNodes(myNode n, TreeNode node)
        {
            foreach (KeyValuePair<string, myNode> pair in ((DirNode)n).subtree)
            {
                if (pair.Value.tp == FileNodeType.DIR_TP)
                {
                    TreeNode nn = new TreeNode(pair.Key);
                    nn.Tag = pair.Key;
                    node.Nodes.Add(nn);
                    ShowProjectFileNodes(pair.Value, nn);
                }
                else
                {
                    TreeNode nn = new TreeNode(pair.Key);
                    nn.Tag = pair.Key;
                    node.Nodes.Add(nn);
                    if (((FileNode)pair.Value).startup) nn.ForeColor = Color.Red;
                }
            }
        }

        private void exportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExportDialog dialog = new ExportDialog();
            dialog.ShowDialog();
        }

        private void CodeVisual_SizeChanged(object sender, EventArgs e)
        {

        }

        private void saveAsPresetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Setting.Save();
        }

        private void createNewProjectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewProjectDialog npd = new NewProjectDialog();
            DialogResult res = npd.ShowDialog();

            if (res == DialogResult.Cancel) return;
            if (res == DialogResult.OK)
            {
                ProjectInfo.reset();
                ProjectInfo.InitProject(npd.textBox1.Text, npd.tp);
                //String s = ProjectInfo.tp.ToString();
                fileTree = new TreeNode(ProjectInfo.name);
                projectTreeView.Nodes.Clear();
                projectTreeView.Nodes.Add(fileTree);
                projectTreeView.SelectedNode = fileTree;
            }

            fileTree.Expand();
            projectTreeView.Select();
            toolStripStatusLabel1.Text = ProjectInfo.path;
        }

        private void saveProjectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ProjectInfo.SaveProject();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (ProjectInfo.rootDir == null)
            {
                MessageBox.Show("Project is not created!");
                return;
            }
            AddFolderDialog d = new AddFolderDialog();
            DialogResult res = d.ShowDialog();
            if (res == DialogResult.OK)
            {
                TreeNode n = projectTreeView.SelectedNode;
                if (n == null)
                {
                    n = projectTreeView.Nodes[0];
                }
                TreeNode folder = new TreeNode(d.folderName);
                n.Nodes.Add(folder);
                string s = n.FullPath;
                ProjectInfo.AddNode(s, d.folderName, FileNodeType.DIR_TP);
                projectTreeView.SelectedNode = folder;
                TreeNode node = new TreeNode(ProjectInfo.name);
                ShowProjectFileNodes(ProjectInfo.rootDir, node);
                projectTreeView.Nodes.Clear();
                node.ImageIndex = 0;
                projectTreeView.Nodes.Add(node);
                //projectTreeView.Sort();
                projectTreeView.ExpandAll();
                //projectTreeView.Select();

                ProjectInfo.modified = true;
            }
        }

        private void importSourceCodeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ImportSrc();
        }

        private void saveProjectAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ProjectInfo.SaveAs();
        }

        private string getFileName(string path)
        {
            if (path == null || path == "") return null;
            string[] s = path.Split('\\');
            return s[s.Length - 1];
        }

        private void loadDefaultToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Setting.LoadDefaultSetting();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (projectTreeView.SelectedNode == null) return;
            TreeNode n = projectTreeView.SelectedNode.Parent;
            if (n == null) return;
            ProjectInfo.RemoveNode(n.FullPath);
            n.Nodes.Remove(projectTreeView.SelectedNode);
        }


        private void button4_Click(object sender, EventArgs e)
        {
            ImportSrc();
        }


        private void ImportSrc()
        {
            if (ProjectInfo.rootDir == null)
            {
                MessageBox.Show("Project is not created!");
                return;
            }
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Multiselect = true;
            DialogResult res = ofd.ShowDialog();
            if (res == DialogResult.OK)
            {
                string[] files = ofd.FileNames;
                foreach (string file in files)
                {
                    string fileName = getFileName(file);
                    TreeNode n = projectTreeView.SelectedNode;
                    TreeNode node = new TreeNode(fileName);
                    node.ImageIndex = 1;
                    if (n != null) n.Nodes.Add(node);
                    string s = n.FullPath;

                    ProjectInfo.AddNode(s, fileName, FileNodeType.FILE_TP, file);
                }
            }

            projectTreeView.ExpandAll();
        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            if (th == null) return;
            DialogResult res = MessageBox.Show("Are you sure to cancel analyse ! ");
            if (res == DialogResult.OK) th.Abort();
        }

        private void setAsEntryPointToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode node = projectTreeView.SelectedNode;
            node.ForeColor = Color.Red;
            myNode n = ProjectInfo.GetNode(node.FullPath);
            ((FileNode)n).startup = true;
            projectTreeView.Refresh();
        }

    }
}